//
//  HJRepairSettlementViewController.m
//  GAMCAfterSales
//
//  Created by 贺佳 on 2018/5/16.
//  Copyright © 2018年 glendale. All rights reserved.
//

#import "HJRepairSettlementViewController.h"

#import "HJRepairSettlementHeaderView.h"
#import "HJSettlementInfoView.h"
#import "HJPrintSettlementSheetView.h"

#import "HJRepairSettlementModel.h"

#import "PrinterHelper.h"

@interface HJRepairSettlementViewController ()<HJSettlementInfoViewDelegate>
/**
 头部
 */
@property(nonatomic,weak)HJRepairSettlementHeaderView*headerView;
/**
 内容详情视图
 */
@property(nonatomic,weak)HJSettlementInfoView*infoView;
/**
 模型
 */
@property(nonatomic,strong)HJRepairSettlementModel*repairSettlementModel;
/**
 打印视图
 */
@property(nonatomic,strong)HJPrintSettlementSheetView*printSheetView;
@end

@implementation HJRepairSettlementViewController
-(HJPrintSettlementSheetView *)printSheetView
{
    if (!_printSheetView) {
        HJPrintSettlementSheetView*sheetView=[[HJPrintSettlementSheetView alloc]initWithFrame:CGRectMake(0, 0, self.view.mj_w, self.view.mj_h)];
        sheetView.hidden=YES;
        _printSheetView=sheetView;
        
        [self.view addSubview:_printSheetView];
    }
    return _printSheetView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self setUI];
    
    [self getData];
}
-(void)getData{
    [SVProgressHUD showWithStatus:@"查询中，请稍后..."];
      NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSDictionary * params = @{
                               @"ENTITY_CODE":[user objectForKey:@"ENTITY_CODE"],
                              @"RO_NO":self.RO_NO};//工单编号
    //api调用及返回
    WEAKSELF;
    [MyAFNetWorkManager postWithParam:params andAction:@"QUERY_REPAIR_ORDER_ITEM_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (error == nil)
        {
            NSLog(@"验车结算 json is %@",obj); HJRepairSettlementModel*repairSettlementModel=[HJRepairSettlementModel mj_objectWithKeyValues:obj];
            weakSelf.repairSettlementModel=repairSettlementModel;
            if(repairSettlementModel.SUCCESS==1){                    [SVProgressHUD showSuccessWithStatus:@"数据查询成功"];
                weakSelf.headerView.repairSettlementModel=repairSettlementModel;
                weakSelf.infoView.repairSettlementModel=repairSettlementModel;
                
                weakSelf.printSheetView.repairSettlementModel=repairSettlementModel;
                
            }else{
                 [SVProgressHUD showErrorWithStatus:@"查询失败"];
            }
            
        }
        else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
        
    }];
}
-(void)setUI{
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
    [backButton setFrame:CGRectMake(50, 30, 45, 60)];
    [backButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    UILabel *jiesuan = [[UILabel alloc]initWithFrame:CGRectMake(160, 50, 200, 40)];
    jiesuan.text = @"维修结算";
    jiesuan.backgroundColor = [UIColor clearColor];
    jiesuan.textColor = [UIColor grayColor];
    jiesuan.font = [UIFont systemFontOfSize:28];
    [self.view addSubview:jiesuan];
    
    //结算与打印
    WEAKSELF;
    UIButton *printBtn = [[UIButton alloc]init];
    [printBtn setTitle:@"结算&打印" forState:UIControlStateNormal];
    printBtn.titleLabel.font=HJFont(13);
    [printBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [printBtn setBackgroundImage:[UIImage imageNamed:@"ht05-1.png"] forState:UIControlStateNormal];
    [printBtn addTarget:self action:@selector(clickPrint) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:printBtn];
    [printBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(100, 32));
        make.right.mas_equalTo(weakSelf.view).inset(100);
        make.centerY.mas_equalTo(jiesuan);
        
    }];
    
    UIImageView *image1 = [[UIImageView alloc]initWithFrame:CGRectMake(40, 100, 950, 11)];
    image1.image = [UIImage imageNamed:@"渐变分割线.png"];
    [self.view addSubview:image1];
    
    //头部
    HJRepairSettlementHeaderView*headerView=[HJRepairSettlementHeaderView new];
    self.headerView=headerView;
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(image1);
        make.height.mas_equalTo(165);
        make.top.mas_equalTo(image1.mas_bottom);
    }];
    
    //内容详情
    HJSettlementInfoView*infoView=[HJSettlementInfoView new];
    [self.view addSubview:infoView];
    infoView.delegate=self;
    self.infoView=infoView;
    [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(headerView);
        make.top.mas_equalTo(headerView.mas_bottom).offset(20);
        make.bottom.mas_equalTo(weakSelf.view);
    }];
    
}
-(void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)clickPrint{
    if (!self.RO_NO) {
        ALERT(@"此单有误,请稍后再试");
        return;
    }
    [SVProgressHUD showWithStatus:@"结算中,请稍后..."];
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    HJRepairSettlementTT_RepairOrderItemModel*repairSettlementTT_RepairOrderItemModel=self.repairSettlementModel.TT_REPAIR_ORDER_ITEM[0];
    NSDictionary * params = @{
                              @"ENTITY_CODE":[user objectForKey:@"ENTITY_CODE"],
                              @"TT_BALANCE_ACCOUNTS.RO_NO":self.RO_NO,
                              @"TT_BALANCE_ACCOUNTS.VIN":repairSettlementTT_RepairOrderItemModel.VIN.length?repairSettlementTT_RepairOrderItemModel.VIN:@"",
                              @"TT_BALANCE_ACCOUNTS.LAB_SUM":self.repairSettlementModel.LABOUR_AMOUNT.length?self.repairSettlementModel.LABOUR_AMOUNT:@"",
                              @"TT_BALANCE_ACCOUNTS.SALE_PAR_SUM":self.repairSettlementModel.PART_AMOUNT.length?self.repairSettlementModel.PART_AMOUNT:@"",
                              @"TT_BALANCE_ACCOUNTS.ADD_ITEM_SALES_SUM":self.repairSettlementModel.ADDITEMA_AMOUNT,
                              @"TT_BALANCE_PAYOBJ.REAL_TOTAL_AMOUNT":self.repairSettlementModel.REAL_RECEVIE,
                              @"TT_BALANCE_PAYOBJ.PAYMENT_OBJECT_CODE":repairSettlementTT_RepairOrderItemModel.OWNER_NO,
                              @"TT_BALANCE_PAYOBJ.PAYMENT_OBJECT_NAME":repairSettlementTT_RepairOrderItemModel.OWNER_NAME,
                              @"TT_BALANCE_ACCOUNTS.DISCOUNT_AMOUNT":self.repairSettlementModel.DISCOUNT_AMOUNT.length?self.repairSettlementModel.DISCOUNT_AMOUNT:@"",
                              @"TT_REPAIR_ORDER.TRACE_TIME":self.printSheetView.thirdTimeLabel.text.length?self.printSheetView.thirdTimeLabel.text:@"",
                              @"TT_REPAIR_ORDER.NO_TRACE_REASON":self.printSheetView.resonLabel.text.length?self.printSheetView.resonLabel.text:@"",
                              @"TT_REPAIR_ORDER.NEXT_MAINTAIN_DATE":self.printSheetView.nextTimeLabel.text.length?self.printSheetView.nextTimeLabel.text:@"",
                              @"TT_REPAIR_ORDER.NEXT_MAINTAIN_MILEAGE":self.printSheetView.nextMileageLabel.text.length?self.printSheetView.nextMileageLabel.text:@""
                              };
    //api调用及返回
    WEAKSELF;
    [MyAFNetWorkManager postWithParam:params andAction:@"ADD_BALANCE_ACCOUNTS_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (error == nil)
        {
            
            if([obj[@"SUCCESS"] integerValue]==1){
                weakSelf.printSheetView.order_snLabel.text=[NSString stringWithFormat:@"NO:%@",obj[@"BALANCE_NO"]];
                //去打印
                [weakSelf connectPrint];
            }else{
                ALERT(@"结算失败");
            }
        }
        else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
        
    }];
   

}
-(void)connectPrint{
//    self.printSheetView.hidden=NO;
    UIImage* image = nil;
    CGSize scrollViewSize=self.printSheetView.contentView.mj_size;
    scrollViewSize.height=scrollViewSize.height-100;
    //        UIGraphicsBeginImageContext(CGSizeApplyAffineTransform(scrollViewSize, CGAffineTransformMakeScale(0.5, 0.5)));
    //        {
    //            CGContextScaleCTM(UIGraphicsGetCurrentContext(), 0.5, 0.5);
    //
    //            CGPoint savedContentOffset = self.myScrollView.contentOffset;
    //            CGRect savedFrame = self.myScrollView.frame;
    //
    //            self.myScrollView.contentOffset = CGPointZero;
    //            self.myScrollView.frame = (CGRect){CGPointZero, _myContenSize};
    //
    //            [self.myScrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
    //            image = UIGraphicsGetImageFromCurrentImageContext();
    //
    //            self.myScrollView.contentOffset = savedContentOffset;
    //            self.myScrollView.frame = savedFrame;
    //        }
    //        UIGraphicsEndImageContext();
    
    UIGraphicsBeginImageContextWithOptions(CGSizeApplyAffineTransform(scrollViewSize, CGAffineTransformMakeScale(0.5, 0.48)),NO, 0);
    {
        CGContextScaleCTM(UIGraphicsGetCurrentContext(), 0.5, 0.5);
        
        CGPoint savedContentOffset = self.printSheetView.scrollView.contentOffset;
        CGRect savedFrame = self.printSheetView.scrollView.frame;
        
        self.printSheetView.scrollView.contentOffset = CGPointZero;
        self.printSheetView.scrollView.frame = (CGRect){CGPointZero, self.printSheetView.contentView.mj_size};
        
        [self.printSheetView.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        
        self.printSheetView.scrollView.contentOffset = savedContentOffset;
        self.printSheetView.scrollView.frame = savedFrame;
    }
    
    UIImageView* tmpImgView = [[UIImageView alloc]initWithImage:image];
    
    PrinterHelper* print = [[PrinterHelper alloc] initWithPrintView:tmpImgView];
}
#pragma mark --HJSettlementInfoViewDelegate
-(void)settlementInfoView:(HJSettlementInfoView *)settlementInfoView changeMileage:(NSString *)mileage
{
    self.printSheetView.nextMileageLabel.text=[NSString stringWithFormat:@"下次保养里程:%@",mileage];
}
-(void)settlementInfoView:(HJSettlementInfoView *)settlementInfoView changeReson:(NSString *)reson
{
    self.printSheetView.resonLabel.text=[NSString stringWithFormat:@"不回访原因:%@",reson];
}
-(void)settlementInfoView:(HJSettlementInfoView *)settlementInfoView changePhoneTime:(NSString *)phoneTime
{
    self.printSheetView.thirdTimeLabel.text=[NSString stringWithFormat:@"三日电访时间:%@",phoneTime];
}
-(void)settlementInfoView:(HJSettlementInfoView *)settlementInfoView changeMaintainTime:(NSString *)maintainTime
{
    self.printSheetView.nextTimeLabel.text=[NSString stringWithFormat:@"下次保养时间:%@",maintainTime];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
